<template>
  <div>
    <!-- 订单维护 -->
    <TopFilter
      :list="topFilterList"
      :cols="3"
      labelWidth="100"
      @filterChange="changeHandle"
      @onCollapse="collapseHandle"
    ></TopFilter>
    <!-- 下方表格 -->
    <FilterTable
      ref="table"
      :columns="columns"
      :fetchapi="fetchApi"
      :params="fetchParams"
      :datakey="'records'"
      :isSelectColumn="false"
      :onColumnsChange="columns => this.columns = columns"
    >
      <template slot="controls">
        <el-button size="small" type="primary"  @click="addHandle">新增</el-button>
      </template>
    </FilterTable>
    <!-- 新增 -->
    <Drawer
      :visible.sync="visible"
      :title="dialogTitle"
      :width="1000"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <DriveModal :type="handleType" :rowData="formData" @close="closeHandler" />
    </Drawer>

    <BaseDialog
      :visible.sync="visible1"
      :title="dialogTitle"
      :cols="1"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <CancelDrive :type="handleType" :rowData="formData1" @close="closeHandler1" />
    </BaseDialog>

    <BaseDialog
      :visible.sync="visible2"
      :title="dialogTitle"
      :cols="1"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <EntryMileage :type="handleType" :rowData="formData2" @close="closeHandler2" />
    </BaseDialog>
    <!-- 审核记录 -->
    <BaseDialog
      :visible.sync="visible3"
      title="审核记录"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <auditRecords :rowData="formData3" @close="closeHandler3" />
    </BaseDialog>

  </div>
</template>
<script>
import { dictionary } from '@/utils/dictMixin';
import DriveModal from './driveModal';
import CancelDrive from './cancelDrive';
import EntryMileage from './entryMileage';
import auditRecords from './auditRecords';
import { getOrders, withdrawOrders, subOrders, toVOrders, deleteOrders, getUsersByPosition } from '@/api/retail/salesmanage/salesordermanage';
import moment from 'moment'
// import { getEmployeeList } from '@/utils/index';
export default {
  name: 'salesordermanage',
  mixins: [dictionary],
  components: {
    DriveModal,
    CancelDrive,
    EntryMileage,
    auditRecords
  },
  data() {
    return {
      topFilterList: this.createTopFilters(),
      fetchParams: {soStatus:""},
      visible: false, //新增
      visible1: false,
      visible2: false,
      visible3: false, //审核记录
      dialogTitle: '',
      fetchApi: getOrders,
      columns: this.createTableColumns(),
      handleType: '',
      formData: {},
      formData1: {},
      formData2: {},
      formData3: {}, //审核记录
      conf: { add: '新增', edit: '编辑', show: '明细'},
      consultantList: []
    };
  },
  created() {
    this.getEmployeeList();
    // getEmployeeList().then(res=>{
    //   this.topFilterList[0].itemList = res
    // })
  },
  methods: {
    createTopFilters() {
      return [
        {
	        type: 'SELECT',
	        label: '销售顾问',
	        fieldName: 'consultant',
	        placeholder: '请选择',
          itemList: [],
	      },
	      {
	        type: 'INPUT',
	        label: '客户订单号',
	        fieldName: 'soNo',
	        placeholder: '请输入...'
	      },
	      {
	        type: 'SELECT',
	        label: '订单状态',
	        fieldName: 'soStatus',
          placeholder: '请选择',
          initialValue: '',
          itemList: [
            {text:'未提交',value: 14041001},
            {text:'经理审核中',value: 14041002},
            {text:'财务审核中',value: 14041015},
            {text:'配车确认中',value: 14041027},
            {text:'已配车确认',value: 14041017},
            {text:'已完成',value: 14041010},
            {text:'经理驳回',value: 14041004},
            {text:'财务驳回',value: 14041016},
            {text:'已撤回',value: 14041014},
          ],
	      },
	      {
	        type: 'SELECT',
	        label: '是否结算',
	        fieldName: 'isClearing',
	        placeholder: '请选择',
          itemList: this.createDictList('1004'),
	      },
	      {
	        type: 'INPUT',
	        label: '客户名称',
	        fieldName: 'customerName',
	        placeholder: '请输入...'
	      },
	      {
	        type: 'INPUT',
	        label: '手机号码',
	        fieldName: 'customerPhone',
	        placeholder: '请输入...'
	      },
	      {
	        type: 'RANGE_DATE',
	        label: '开单日期',
	        fieldName: 'sheetCreateDateStart|sheetCreateDateEnd',
	        placeholder: '请选择日期...'
	      }
      ];
    },
    createTableColumns() {
      return [
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 260,
          fixed: 'left',
          render: (props, h) => {
            let list = []
            if (props.row.soStatus !== 14041001) {
              list.push({type: '明细', funcAction: () => this.showHandle(props.row)})
            }
            if ([14041002, 14041015].indexOf(props.row.soStatus) !== -1) {
              list.push({type: '撤回', funcAction: () => this.withdrawHandle(props.row)})
            }
            if ([14041001, 14041004, 14041014, 14041016].indexOf(props.row.soStatus) !== -1) {
              list = [].concat(list, [
                {type: '编辑', funcAction: () => this.editHandle(props.row)},
                {type: '提交', funcAction: () => this.subwHandle(props.row)}
              ])
            }
            if (props.row.soStatus !== 14041001) {
              list.push({type: '审核记录', funcAction: () => this.recordHandle(props.row)})
            }
            if ([14041004, 14041014, 14041016].indexOf(props.row.soStatus) !== -1) {
              list.push({type: '作废', funcAction: () => this.toVoidHandle(props.row)})
            }
            if ([14041001].indexOf(props.row.soStatus) !== -1) {
              list.push({type: '删除', funcAction: () => this.deleteHandle(props.row)})
            }
            let resultHTML = []
            for (let item in list) {
                resultHTML.push(<el-button size="mini" type="text" onClick={ list[item].funcAction }>
                  {list[item].type}
                </el-button>)
                // typeof item === 'string'
                if (list.length-1 != item){
                  resultHTML.push(<el-divider direction="vertical" />)
                }
            }
            resultHTML.join(<el-divider direction="vertical" />)
            return (
              <div>{ resultHTML }</div>
            );
          }
        },
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          fixed: 'left',
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
	        title: '客户订单号',
	        dataIndex: 'soNo',
	        sorter: true,
	        filter: true,
	        filterType: 'input',
	      },
	      {
	        title: '订单状态',
	        dataIndex: 'soStatus',
	        sorter: true,
	        filter: true,
	        filterType: 'checkbox',
	        filterItems: this.createDictList('1404'),
	        render: props => {
	          return <span>{this.createDictText(props.row.soStatus, '1404')}</span>;
	        }
	      },
	      {
	        title: '客户名称',
	        dataIndex: 'customerName',
	        sorter: true,
	        filter: true,
	        filterType: 'input'
	      },
	      {
	        title: '销售顾问',
	        dataIndex: 'userName',
	        sorter: true,
	        filter: true,
	        filterType: 'input'
	      },
	      {
	        title: '手机号码',
	        dataIndex: 'mobile',
	        sorter: true,
	        filter: true,
	        filterType: 'input'
	      },
	      {
	        title: '出库状态',
	        dataIndex: 'outStatus',
	        sorter: true,
	        filter: true,
	        filterType: 'input',
	        filterItems: this.createDictList('1415'),
	        render: props => {
	          return <span>{this.createDictText(props.row.outStatus, '1415')}</span>;
	        }
	      },
	      {
	        title: '是否结清',
	        dataIndex: 'isClearing',
	        sorter: true,
	        filter: true,
	        filterType: 'input',
	        filterItems: this.createDictList('1004'),
	        render: props => {
	          return <span>{this.createDictText(props.row.isClearing, '1004')}</span>;
	        }
	      },
	      {
	        title: '开单人',
	        dataIndex: 'sheetCreatedBy',
	        sorter: true,
	        filter: true,
	        filterType: 'input'
	      },
	      {
	        title: '开单日期',
	        dataIndex: 'sheetCreateDate',
	        sorter: true,
	        filter: true,
	        render: props =>{
            return <span>{ this.preDateHandler(props.row.sheetCreateDate, 'YYYY-MM-DD') } </span>
          }
	      },
	      {
	        title: '创建方式',
	        dataIndex: 'loginWay',
	        sorter: true,
	        filter: true,
          filterType: 'input'
	      },

      ];
    },
    addHandle() {
      this.handleType = 'add';
      this.formData = {};
      this.showHandler();
    },
    editHandle(row) {
      console.log('编辑', row);
      this.handleType = 'edit';
      this.formData = row;
      this.formData.testDriveFileDTOList = row.drivingDisclaimer
      this.showHandler();
    },
    showHandle(row) { //明细
      console.log('查看', row);
      this.handleType = 'show';
      this.formData = row;
      this.showHandler();
    },
    showHandle1(row) { //待写
      console.log('待写', row);
    },
    subwHandle (row){ //订单重新提交
      // console.log(row)
      this.$confirm('此操作将提交该条数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log(row)
        subOrders(row.soNoId).then(res => {
          console.log(res)
          if(res.resultCode == 200){
            // this.$message({
            //   type: 'success',
            //   message: '提交成功!'
            // });
            this.fetchParams = { ...this.fetchParams };
          }
        }).catch(err => {
          console.log(err)
        })
      }).catch(() => {
        console.log('取消')
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    },
    recordHandle (row){ //审核记录
      console.log(row)
      this.formData3 = row;
      this.visible3 = true;
    },
    withdrawHandle (row){ //撤回订单
      // console.log(row)
      this.$confirm('此操作将撤回该条数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        withdrawOrders(row.soNoId).then(res => {
          if(res.resultCode == 200){
            this.$message({
              type: 'success',
              message: '撤回成功!'
            });
            this.fetchParams = { ...this.fetchParams };
          }
        }).catch(err => {
          console.log(err)
        })

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    },
    toVoidHandle (row){ //作废订单
      console.log(row)
      this.$confirm('此操作将作废该条数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        toVOrders(row.soNoId).then(res => {
          if(res.resultCode == 200){
            this.$message({
              type: 'success',
              message: '作废成功!'
            });
            this.fetchParams = { ...this.fetchParams };
          }
        }).catch(err => {
          console.log(err)
        })

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    },
    deleteHandle (row){ //删除订单
      console.log(row)
      this.$confirm('此操作将删除该条数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteOrders(row.soNoId).then(res => {
          if(res.resultCode == 200){
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.fetchParams = { ...this.fetchParams };
          }
        }).catch(err => {
          console.log(err)
        })

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    },
    showHandler() {
      this.dialogTitle = `客户订单${this.conf[this.handleType]}`;
      this.visible = true;
    },
    showHandler1() {
      this.dialogTitle = `${this.conf[this.handleType]}`;
      this.visible1 = true;
    },
    showHandler2() {
      this.dialogTitle = `${this.conf[this.handleType]}`;
      this.visible2 = true;
    },
    changeHandle(val) {
      this.fetchParams = Object.assign({}, val);
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    closeHandler(val, type) {
      this.visible = val;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },
    closeHandler1(val, type) {
      this.visible1 = val;
      if (type === 'refresh') {
        console.log(111, type);
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },
    closeHandler2(val, type) {
      this.visible2 = val;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },
    closeHandler3 (val){ //审核记录
      this.visible3 = val;
      // this.fetchParams = { ...this.fetchParams }; // 重新加载
    },
    async getEmployeeList() {
      let params = {
        positionCodes: [10061015],
        menuId: 223001
      }
      const res = await getUsersByPosition(params);
      // console.log('销售顾问', res)
      if (res.resultCode === 200) {
        let orginList = res.data.map(x => ({ value: x.userId, text: x.userName }));
        this.consultantList = orginList.filter((item,index,array) => {
          return array.findIndex(el=>el.value==item.value)===index
        })
        this.topFilterList.find(item => item.fieldName == 'consultant').itemList = this.consultantList;
      }
    },
    // 日期预处理
    preDateHandler(val, formatCode='YYYY-MM-DD HH:mm:ss') {
      let resultDate = val ? moment(Number(val)).format(formatCode) : val;
      if ((resultDate == 'Invalid date' || resultDate == 'Invalid Date') && val) {
        resultDate = moment(val).format(formatCode)
      }
      return resultDate;
    },
  },
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
  }
};
</script>

<style lang="less" scoped>
</style>
